param(
    [string]$vcxprojPath,
    [string]$sourceDirectory
)

# Load the Visual Studio Project XML
[xml]$projectXml = Get-Content $vcxprojPath

# Namespace management
$ns = @{msb="http://schemas.microsoft.com/developer/msbuild/2003"}
$manager = New-Object System.Xml.XmlNamespaceManager($projectXml.NameTable)
$manager.AddNamespace("msb", $ns.msb)

# Identify the ItemGroup for ClCompile and ClInclude separately
$compileGroup = $projectXml.SelectSingleNode("//msb:ItemGroup[msb:ClCompile[contains(@Include, 'main.c')]]", $manager)
$includeGroup = $projectXml.SelectSingleNode("//msb:ItemGroup[msb:ClInclude]", $manager)

# Remove old source-related entries
$compileGroup.SelectNodes("msb:ClCompile[contains(@Include, 'model\sources\')]", $manager) | ForEach-Object {
    $compileGroup.RemoveChild($_) | Out-Null
}
$includeGroup.SelectNodes("msb:ClInclude[contains(@Include, 'model\sources\')]", $manager) | ForEach-Object {
    $includeGroup.RemoveChild($_) | Out-Null
}

# Add new .c files to the compile group
Get-ChildItem -Path $sourceDirectory -Filter "*.c" -Recurse | ForEach-Object {
    $relativePath = "model\sources\" + $_.Name
    $newCompile = $projectXml.CreateElement("ClCompile", $ns.msb)
    $newCompile.SetAttribute("Include", $relativePath)
    $compileGroup.AppendChild($newCompile) | Out-Null
}

# Add new .h files to the include group
Get-ChildItem -Path $sourceDirectory -Filter "*.h" -Recurse | ForEach-Object {
    $relativePath = "model\sources\" + $_.Name
    $newInclude = $projectXml.CreateElement("ClInclude", $ns.msb)
    $newInclude.SetAttribute("Include", $relativePath)
    $includeGroup.AppendChild($newInclude) | Out-Null
}

# Save the updated project file
$projectXml.Save($vcxprojPath)
